﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;

using Shop.Intermediate;
using DoNet.Common.Utilities;

namespace Shop.Core.Configuration
{
    internal static class IDataProviderConfigurationExtensions
    {
        public static IDataProvider GetInstance(this IDataProviderConfiguration dataProviderConfiguration)
        {
            string[] typeParts = dataProviderConfiguration.Type.Split(',');
            object o = DataCache.GetCache(typeParts[0]);
            if (o == null)
            {   
                string typeName = Assembly.CreateQualifiedName(typeParts[1].Trim(), typeParts[0].Trim());
                Type type = Type.GetType(typeName, true);
                string connString = ConfigurationManager.ConnectionStrings[
                                                                 dataProviderConfiguration.ConnectionStringName].ConnectionString;
                o = Activator.CreateInstance(type,
                                                     new object[]
                                                     {
                                                        connString
                                                     });
                DataCache.SetCache(typeParts[0],o);
            }
            return o as IDataProvider;
        }
    }

}
